package com.shjy.driver.jg;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;

import com.shjy.driver.R;
import com.shjy.driver.activity.DetailActivity;
import com.shjy.driver.xf.XFUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * 
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class JGReceiver extends BroadcastReceiver {

	private static final String TAG = "JGReceiver";

	private static String pushTitle = "";
	private static String pushID = "";

	@Override
	public void onReceive(Context context, Intent intent) {
		pushTitle = "";
		pushID = "";
		try {
			Bundle bundle = intent.getExtras();
			Log.d(TAG, "onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

			if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
				String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
				Log.d(TAG, "Registration Id : " + regId);
			} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
				Log.d(TAG, "接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
			} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
				playDing(context);

				Timer timer = new Timer();
				timer.schedule(new Task(context), 6000);//3秒后执行TimeTask的run方法

			} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
				Log.d(TAG, "用户点击打开了通知 pushID [" + pushID + "] " + context);

				// 打开自定义的Activity
				Intent i = new Intent(context, DetailActivity.class);
				i.putExtra("url", "driver/bid/bid_detail.html?waybillId=" + pushID);
				i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(i);
			} else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
				Log.d(TAG, "用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
			} else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
				boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
				Log.w(TAG, "" + intent.getAction() +" connected state change to "+connected);
			} else {
				Log.d(TAG, "Unhandled intent - " + intent.getAction());
			}
		} catch (Exception e){

		}
	}

	class Task extends TimerTask{
		private Context context;
		public Task(Context context){
			this.context = context;
		}
		@Override
		public void run(){
			/**
			 *要执行的操作
			 */
			// 讯飞语音播报
			if (!TextUtils.isEmpty(pushTitle)) {
				XFUtil.speak(context, pushTitle);
			}

			// 自动打开自定义的Activity
			if(pushID!=null && !"".equals(pushID) && !"0".equals(pushID) && pushID.length()>1) {
				Intent i = new Intent(context, DetailActivity.class);
				i.putExtra("url", "driver/bid/bid_detail.html?waybillId=" + pushID);
				i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(i);
			}
		}
	}


	public void playDing(Context mContext) {
		NotificationManager nm = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
		Uri ringUri = Uri.parse("android.resource://" + mContext.getPackageName() + "/"+ R.raw.ding);//RingtoneManager.getDefaultUri(ringType);
		Notification notification = new NotificationCompat.Builder(mContext)
				.setTicker("开始接单").setSound(ringUri)
				.setContentTitle("开始接单").setContentText("开始接单").setSound(ringUri).build();
		Ringtone r = RingtoneManager.getRingtone(mContext, ringUri);
		r.play();
	}

	// 打印所有的 intent extra 数据
	private static String printBundle(Bundle bundle) {
		StringBuilder sb = new StringBuilder();
		for (String key : bundle.keySet()) {
			if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
			}else if(key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)){
				sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
			} else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
				if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
					Log.i(TAG, "This message has no Extra data");
					continue;
				}
				try {
					JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
					Iterator<String> it =  json.keys();

					while (it.hasNext()) {
						String myKey = it.next().toString();
						sb.append("\nkey:" + key + ", value: [" +
								myKey + " - " +json.optString(myKey) + "]");
						if (TextUtils.equals(myKey, "id")) {
							pushID = json.optString(myKey);
						}
					}
				} catch (JSONException e) {
					Log.e(TAG, "Get message extra JSON error!");
				}

			} else {
				sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
				if (TextUtils.equals(key, "cn.jpush.android.ALERT")) {
					pushTitle = bundle.getString(key);
				}
				if (TextUtils.equals(key, "cn.jpush.android.TITLE")) {
					pushTitle = bundle.getString(key);
				}
			}
		}
		return sb.toString();
	}
}
